package org.edu.modules.growth.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.edu.common.api.vo.Result;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.util.DateUtils;
import org.edu.modules.growth.config.AccidentTypeEnum;
import org.edu.modules.growth.config.ConstantTool;
import org.edu.modules.growth.config.MathTool;
import org.edu.modules.growth.dto.VeJsczAccidentDTO;
import org.edu.modules.growth.entity.VeJsczAccident;
import org.edu.modules.growth.entity.bo.VeBaseFacultBO;
import org.edu.modules.growth.service.IVeBaseManageService;
import org.edu.modules.growth.service.IVeJsczAccidentService;
import org.edu.modules.growth.vo.AccidentStasticsVo;
import org.edu.modules.growth.vo.DictVo;
import org.edu.modules.growth.vo.QueryCondition;
import org.edu.modules.growth.vo.VeJsczAccidentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags="教学事故管理")
@RestController
@RequestMapping("jsczAccident")
@Slf4j
@AllArgsConstructor
public class VeJsczAccidentController extends BaseController<VeJsczAccident, IVeJsczAccidentService> {

    private IVeJsczAccidentService mIVeJsczAccidentService ;

    private IVeBaseManageService mIVeBaseManageService ;

    /**
     * 查询教学事故字典
     */
    @ApiOperation(value = "查询教学事故字典")
    @GetMapping("/getDictSGJB")
    public Result<List<DictVo>> getDictSGJB( ) {
        return Result.OK(AccidentTypeEnum.getDict());
    }


    /**
     * 事故录入
     */
    @ApiOperation(value = "教学事故录入")
    @PostMapping("/accidentRecode")
    public Result<?> accidentRecode(@RequestBody VeJsczAccidentDTO veJsczAccidentDTO ) {
        VeJsczAccident ve = new VeJsczAccident() ;
        String time = DateUtils.formatDate(veJsczAccidentDTO.getAccidentTime()*1000) ;
        Integer year = Integer.parseInt(time.split("-")[0]) ;
        BeanUtils.copyProperties(veJsczAccidentDTO, ve);
        ve.setCreateTime(System.currentTimeMillis()/1000).setYear(year).setTerminalId(1L) ;
//        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        ve.setCreateUserId(Long.parseLong(user.getId())) ;
        return Result.OK(mIVeJsczAccidentService.save(ve));
    }

    /**
     * 分页查询信息
     */
    @ApiOperation(value = "分页查询信息")
    @PostMapping("/selectPage")
    public Result<?> selectPage(@RequestBody QueryCondition queryCondition ) {
        return Result.OK(mIVeJsczAccidentService.selectPage(queryCondition));
    }

    /**
     * 根据事故id查询教师及事故详情信息
     */
    @ApiOperation(value = "根据事故id查询教师及事故详情信息")
    @PostMapping("/getDetail")
    public Result<VeJsczAccidentVo> getDetail(@RequestParam("id") Long id) {
        VeJsczAccident v = mIVeJsczAccidentService.getById(id) ;
        VeJsczAccidentVo vo = new VeJsczAccidentVo() ;
        BeanUtils.copyProperties(v,vo) ;
        return Result.OK(vo);
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除")
    @PostMapping("/removeById")
    public Result<?> removeById(@RequestParam("id") Long id) {
        return Result.OK(mIVeJsczAccidentService.removeById(id));
    }

    /**
     * 批量删除
     */
    @ApiOperation(value = "批量删除")
    @PostMapping("/removeByIds")
    public Result<?> removeByIds(@RequestBody List<Long> ids) {
        if( !CollectionUtils.isEmpty(ids) ){
            return Result.OK(mIVeJsczAccidentService.removeByIds(ids));
        }
        return Result.error( "传输参数为空！" );
    }

    /**
     * 编辑
     */
    @ApiOperation(value = "编辑信息")
    @PostMapping("/update")
    public Result<?> update(@RequestBody VeJsczAccidentDTO dto) {
        if( dto.getId() != null ){
            VeJsczAccident c = new VeJsczAccident() ;
            BeanUtils.copyProperties(dto, c);
            VeJsczAccident ve = mIVeJsczAccidentService.getById(dto.getId()) ;
            // 仅未认定的才可修改
            if(ve.getCheckStatus().equals(ConstantTool.TEACHACCIDENTSTATUS.BEGIN)){
                // 有修改事故发生时间
                if( c.getAccidentTime() != null && c.getAccidentTime() > 0){
                    String time = DateUtils.formatDate(c.getAccidentTime()*1000) ;
                    Integer year = Integer.parseInt(time.split("-")[0]) ;
                    c.setYear(year) ;
                }
                return Result.OK(mIVeJsczAccidentService.updateById(c));
            }
        }
        return Result.error("传输信息有误！");
    }

    /**
     * 督导处认定操作
     */
    @ApiOperation(value = "督导处认定操作")
    @PostMapping("/supervisionOperate")
    public Result<?> supervisionOperate(@RequestParam("id") Long id, @RequestParam("result") Integer result,
                           @RequestParam("view") String view) {
        List<Integer> resultList = Lists.newArrayList(ConstantTool.TEACHACCIDENTRESULT.PASS,
                ConstantTool.TEACHACCIDENTRESULT.NOPASS) ;
        if( resultList.contains(result) ){
            // 数据校验
            VeJsczAccident accident = mIVeJsczAccidentService.getById(id) ;
            if( accident != null && accident.getCheckStatus().equals(
                    ConstantTool.TEACHACCIDENTSTATUS.BEGIN)){
                VeJsczAccident ve = new VeJsczAccident() ;
                ve.setJwcCheckTime(System.currentTimeMillis()/1000)
                        .setId(id).setJwcSuggest(view).setJwcCheckStatus(result);
                // 认定通过
                if( ConstantTool.TEACHACCIDENTRESULT.PASS.equals(result) ){
                    ve.setCheckStatus(ConstantTool.TEACHACCIDENTSTATUS.IN) ;
                }else{
                    ve.setCheckStatus(ConstantTool.TEACHACCIDENTSTATUS.END)
                            .setCheckResult(ConstantTool.TEACHACCIDENTRESULT.NOPASS);
                }
                return Result.OK(mIVeJsczAccidentService.updateById(ve));
            }
        }
        return Result.error("传输信息有误！");
    }

    /**
     * 校长认定操作
     */
    @ApiOperation(value = "校长认定操作")
    @PostMapping("/headmasterOperate")
    public Result<?> headmasterOperate(@RequestParam("id") String sid, @RequestParam("result") Integer result,
                                        @RequestParam("view") String view) {
        List<Integer> resultList = Lists.newArrayList(ConstantTool.TEACHACCIDENTRESULT.PASS,
                ConstantTool.TEACHACCIDENTRESULT.NOPASS) ;
        Long id = Long.parseLong(sid.trim()) ;
        if( resultList.contains(result) ){
            // 数据校验
            VeJsczAccident accident = mIVeJsczAccidentService.getById(id) ;
            if( accident != null && accident.getCheckStatus().equals( ConstantTool.TEACHACCIDENTSTATUS.IN)){
//                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                VeJsczAccident ve = new VeJsczAccident() ;
                ve.setXzCheckTime(System.currentTimeMillis()/1000).setXzSuggest(view)
                        .setId(id).setXzCheckStatus(result)
                .setCheckResult(result).setCheckStatus(ConstantTool.TEACHACCIDENTSTATUS.END);
//                ve.setXzCheckUserId(Long.parseLong(user.getId())) ;
                return Result.OK(mIVeJsczAccidentService.updateById(ve));
            }
        }
        return Result.error("传输信息有误！");
    }

    /**
     * 院系统计查询
     */
    @ApiOperation(value = "院系统计查询")
    @PostMapping("/fallStatistics")
    @ApiImplicitParam(paramType = "query", name = "semId", value = "学期Id", dataType = "Long")
    public Result<List<AccidentStasticsVo>> fallStatistics(@RequestParam("semId") Long semId) {
        //获取所有院系信息
        List<VeBaseFacultBO> f = mIVeBaseManageService.facultAll().getResult() ;
        Map<Long,List<VeBaseFacultBO>> fMap = f.stream().collect(Collectors.groupingBy(VeBaseFacultBO::getId ) );
        Map<String,Object> map = Maps.newHashMap() ;
        map.put("semId",semId) ;
        map.put("checkResult",1) ;
        List<VeJsczAccident> list = mIVeJsczAccidentService.listByMap(map) ;
        Integer all = list.size() ;
        Map<Long,List<VeJsczAccident>> mapr = list.stream().collect(Collectors.groupingBy(VeJsczAccident::getFalId)) ;
        List<AccidentStasticsVo> res = Lists.newArrayList() ;
        fMap.forEach((k,v)->{
            AccidentStasticsVo vo = new AccidentStasticsVo();
            VeBaseFacultBO b = v.get(0) ;
            List<VeJsczAccident> l = mapr.getOrDefault(k,Lists.newArrayList()) ;
            vo.setId(k).setNum(l.size()).setRatio(MathTool.getPercent(l.size(),all,0)).setName(b.getYxmc()) ;
            res.add(vo) ;
        });
        // 其他
        int a = all - res.stream().mapToInt(AccidentStasticsVo::getNum).sum() ;
        res.add(new AccidentStasticsVo().setName("其他").setNum(a).setRatio(MathTool.getPercent(a,all,0))) ;

        return Result.OK(res);
    }

    /**
     * 教研组统计查询
     */
    @ApiOperation(value = "教研组统计查询")
    @PostMapping("/jtzStatistics")
    @ApiImplicitParam(paramType = "query", name = "semId", value = "学期Id", dataType = "Long")
    public Result<List<AccidentStasticsVo>> jtzStatistics(@RequestParam("semId") Long semId) {
        Map<String,Object> map = Maps.newHashMap() ;
        map.put("semId",semId) ;
        map.put("checkResult",1) ;
        List<VeJsczAccident> list = mIVeJsczAccidentService.listByMap(map) ;
        Integer all = list.size() ;
        Map<Long,List<VeJsczAccident>> mapr = list.stream().collect(Collectors.groupingBy(VeJsczAccident::getJyzId)) ;
        List<AccidentStasticsVo> res = Lists.newArrayList() ;
        mapr.forEach((k,v)->{
            AccidentStasticsVo vo = new AccidentStasticsVo();
            vo.setId(k).setNum(v.size()).setRatio(MathTool.getPercent(v.size(),all,0)) ;
            res.add(vo) ;
        });
        // 其他
//        int a = all - res.stream().mapToInt(AccidentStasticsVo::getNum).sum() ;
//        res.add(new AccidentStasticsVo().setName("其他").setNum(a).setRatio(MathTool.getPercent(a,all,0))) ;
        return Result.OK(res);
    }




}
